package com.km.wskj.itmonitor.pager.news;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.fingdo.statelayout.StateLayout;
import com.km.wskj.itmonitor.R;
import com.km.wskj.itmonitor.http.ZxlGenericsCallback;
import com.km.wskj.itmonitor.model.Imgs;
import com.km.wskj.itmonitor.model.NewsColumns;
import com.km.wskj.itmonitor.model.NewsItem;
import com.km.wskj.itmonitor.pager.base.LFragment;
import com.zxl.zxlapplibrary.adapter.BaseAdapterHelper;
import com.zxl.zxlapplibrary.global.Constant;
import com.zxl.zxlapplibrary.util.LogUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import zrc.widget.SimpleFooter;
import zrc.widget.SimpleHeader;
import zrc.widget.ZrcListView;


public class NewsListFragment extends LFragment implements StateLayout.OnViewRefreshListener {
    private static final String TAG = "KnowledgeListFragment";

    //data
    private NewsColumns mNewsColumns;
    private List<NewsItem> mNewsLists;
    private int lastUpdateNum;
    private int pageIndex;

    private MyAdapter mAdapter;
    //ui
    @BindView(R.id.knowledge_list_zrcListView)
    ZrcListView mZrcListView;
    @BindView(R.id.state_layout)
    StateLayout stateLayout;


    public static NewsListFragment getInstance(NewsColumns newsColumns) {
        NewsListFragment sf = new NewsListFragment();
        sf.mNewsColumns = newsColumns;
        return sf;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_knowledge_list, null);
        ButterKnife.bind(this, view);
        stateLayout.setRefreshListener(this);
        initData();
        return view;
    }

    private void initData() {
        stateLayout.showLoadingView();
        if (mNewsColumns == null)
            return;

        pdc.newsList(HTTP_TASK_TAG, 1, Constant.PageListSize, mNewsColumns.id, null, new ZxlGenericsCallback<List<NewsItem>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
                stateLayout.showErrorView();
            }

            @Override
            public void onResponse(List<NewsItem> newsLists, int i) {
                if (newsLists.size() == 0)
                    stateLayout.showEmptyView();

                mNewsLists = newsLists;
                lastUpdateNum = newsLists.size();
                pageIndex = 1;
                //control
                mAdapter.notifyDataSetChanged();
                mZrcListView.setRefreshSuccess();

                if (haveMore())
                    mZrcListView.startLoadMore();
                else
                    mZrcListView.stopLoadMore();
            }
        });
        initPullToRefresh();
    }

    private void initPullToRefresh() {
        //配置listview
        ColorDrawable line = new ColorDrawable(Color.parseColor("#eeeeee"));
        mZrcListView.setDivider(line);
        mZrcListView.setDividerHeight(1);

        //设置下拉刷新的样式（可选，但如果没有Header则无法下拉刷新）
        SimpleHeader header = new SimpleHeader(getActivity());
        header.setTextColor(ContextCompat.getColor(getContext(), R.color.text_gray));
        header.setCircleColor(ContextCompat.getColor(getContext(), R.color.colorPrimary));
        mZrcListView.setHeadable(header);

        //设置加载更多的样式（可选）
        SimpleFooter footer = new SimpleFooter(getContext());
        footer.setCircleColor(ContextCompat.getColor(getContext(), R.color.colorPrimary));
        mZrcListView.setFootable(footer);

        // 设置列表项出现动画（可选）
        //zListView.setItemAnimForTopIn(R.anim.topitem_in);
        mZrcListView.setItemAnimForBottomIn(R.anim.bottomitem_in);

        // 下拉刷新事件回调（可选）
        mZrcListView.setOnRefreshStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                onRefresh();
            }
        });

        // 加载更多事件回调（可选）
        mZrcListView.setOnLoadMoreStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                onLoadMore();
            }
        });

        // 项目选中
        mZrcListView.setOnItemClickListener(new ZrcListView.OnItemClickListener() {
            @Override
            public void onItemClick(ZrcListView parent, View view, int position, long id) {
                NewsItem kl = (NewsItem) parent.getItemAtPosition(position);
                Intent t = new Intent(getActivity(), NewsDetailActivity.class);
                t.putExtra("data", kl);
                t.putExtra("id", kl.id);
                startActivity(t);

            }
        });

        mAdapter = new MyAdapter();
        mZrcListView.setAdapter(mAdapter);
        stateLayout.showContentView();
    }

    private void onRefresh() {
        pdc.newsList(HTTP_TASK_TAG, 1, Constant.PageListSize, mNewsColumns.id, null, new ZxlGenericsCallback<List<NewsItem>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
                stateLayout.showErrorView();
            }

            @Override
            public void onResponse(List<NewsItem> newsLists, int i) {
                if (newsLists.size() == 0)
                    stateLayout.showEmptyView();

                mNewsLists = newsLists;
                lastUpdateNum = newsLists.size();
                pageIndex = 1;
                //control
                mAdapter.notifyDataSetChanged();
                mZrcListView.setRefreshSuccess();

                if (haveMore())
                    mZrcListView.startLoadMore();
                else
                    mZrcListView.stopLoadMore();
            }
        });
    }

    private void onLoadMore() {
        pdc.newsList(HTTP_TASK_TAG, pageIndex + 1, Constant.PageListSize, mNewsColumns.id, null, new ZxlGenericsCallback<List<NewsItem>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
                stateLayout.showErrorView();
            }

            @Override
            public void onResponse(List<NewsItem> newsLists, int i) {
                lastUpdateNum = newsLists.size();
                if (newsLists.size() > 0) {
                    mNewsLists.addAll(newsLists);
                    pageIndex++;
                }

                //control
                mAdapter.notifyDataSetChanged();
                mZrcListView.setLoadMoreSuccess();
                if (haveMore())
                    mZrcListView.startLoadMore();
                else
                    mZrcListView.stopLoadMore();
            }
        });

    }

    private boolean haveMore() {
        return lastUpdateNum > 0;
    }

    @Override
    public void refreshClick() {
        initData();
    }

    @Override
    public void loginClick() {

    }

    /**
     * 适配器
     */
    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            if (mNewsLists == null) {
                return 0;
            }
            return mNewsLists.size();
        }

        @Override
        public Object getItem(int position) {
            NewsItem item = mNewsLists.get(position);
            return item;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getViewTypeCount() {
            return 1;
        }

        @Override
        public int getItemViewType(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            NewsItem item = mNewsLists.get(position);
            int size = item.imgs.size();
            final BaseAdapterHelper helper;
            //没图片
            if (size == 0) {
                helper = BaseAdapterHelper.get(getContext(), convertView, parent, R.layout.item_knowledge_one);
                helper.setVisible(R.id.iv_img, false);
                helper.setText(R.id.tv_title, item.title);
                helper.setText(R.id.tv_author, item.author != null ? item.author : item.source);
                helper.setText(R.id.tv_create_time, item.createTime);


                //三张以上图片显示三张
            } else if (size >= 3) {
                helper = BaseAdapterHelper.get(getContext(), convertView, parent, R.layout.item_knowledge_three);
                helper.setText(R.id.tv_title, item.title);
                helper.setText(R.id.tv_create_time, item.createTime);
                helper.setText(R.id.tv_author, item.author != null ? item.author : item.source);

                Imgs imgs1 = item.imgs.get(0);
                Imgs imgs2 = item.imgs.get(1);
                Imgs imgs3 = item.imgs.get(2);

                Glide.with(getActivity())
                        .load(imgs1.host + imgs1.file_path + imgs1.new_file_name)
                        .asBitmap()
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                helper.setImageBitmap(R.id.iv_img1, resource);
                            }

                            @Override
                            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                                super.onLoadFailed(e, errorDrawable);
                                LogUtils.e("LLpp:加载失败");
                            }
                        }); //方法中设置asBitmap可以设置回调类型

                Glide.with(getActivity())
                        .load(imgs2.host + imgs2.file_path + imgs2.new_file_name)
                        .asBitmap()
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                helper.setImageBitmap(R.id.iv_img2, resource);
                            }

                            @Override
                            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                                super.onLoadFailed(e, errorDrawable);
                                LogUtils.e("LLpp:加载失败");
                            }
                        }); //方法中设置asBitmap可以设置回调类型

                Glide.with(getActivity())
                        .load(imgs3.host + imgs3.file_path + imgs3.new_file_name)
                        .asBitmap()
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                helper.setImageBitmap(R.id.iv_img3, resource);
                            }

                            @Override
                            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                                super.onLoadFailed(e, errorDrawable);
                                LogUtils.e("LLpp:加载失败");
                            }
                        }); //方法中设置asBitmap可以设置回调类型

                //三张以下=图片显示一张
            } else {
                helper = BaseAdapterHelper.get(getContext(), convertView, parent, R.layout.item_knowledge_one);
                helper.setText(R.id.tv_title, item.title);
                helper.setText(R.id.tv_create_time, item.createTime);
                helper.setText(R.id.tv_author, item.author != null ? item.author : item.source);

                Imgs imgs = item.imgs.get(0);

                Glide.with(getActivity())
                        .load(imgs.host + imgs.file_path + imgs.new_file_name)
                        .asBitmap()
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                helper.setImageBitmap(R.id.iv_img, resource);
                            }

                            @Override
                            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                                super.onLoadFailed(e, errorDrawable);
                                LogUtils.e("LLpp:加载失败");
                            }
                        }); //方法中设置asBitmap可以设置回调类型

            }


            return helper.getView();
        }
    }
}